﻿   // #define Debug_ITAC
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AMStudio.DelegateDispather;
using AMStudio.Script;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System.Text.RegularExpressions;
using System.Threading;
using System.Data;
using AccessDB;


namespace AMStudio.Common
{

    public class ScriptManager : GeneralManager
    {
        //protected int trac_taskid = -1;
        //protected CustomerSnMaker.CustomerSnProcess cust_dll = new CustomerSnMaker.CustomerSnProcess("");
        //protected BomTest.bomTest bom_dll = new BomTest.bomTest();
        //protected int CUSTSN_MARGIN_LEN = 20;

        string sn = string.Empty;
        string customerSn = string.Empty;
        string lastCSN = string.Empty;
        string newMaterialNr = string.Empty;
        string materialBinNr = string.Empty;
        double quantity = 0;
        //todo PRODUCT 加个满箱数量
        double totalQuantity = 216;
        int delayActive = 0;
        Queue<string> customerSnQueue = new Queue<string>();
        DataTable st1MaterialArray;
        DataTable activeMaterialArray;
        private bool bEmptyLine = false;
        private bool bTrialRun = false;
        private bool bRework = false;

        #region 声明相机模板检查变量
        bool bProductCheck = false;
        bool bStn5ProductCheckResultOK = true;
        bool bStn5ProductCheckResultNG = true;
        bool bLastProductCheck = false;
        string current_recipe = string.Empty;
        #endregion

        private System.DateTime lastTime;
        private List<double> cycleList = new List<double>();
        protected override void InitProcess()
        {
            base.InitProcess();

            //st12 ready
            WritePLC(DialTablePLC, "E2381.15", "True");
            WritePLC(DialTablePLC, "E2381.14", "True");

            SendFeedBack("EMPTY_LINE", true, false);
            SendFeedBack("TRIAL_RUN", true, false);
            SendFeedBack("REWORK", true, false);
            WritePLC(DialTablePLC, "E2221.06", "False");

            WorkorderDB.GetActiveWorkOrder();
            ProductSettings s = WorkorderDB.ActiveProduct;
            if (s != null)
                currentProductSettings = s;

            //Driver.IExecuteReader IR = St12Trace.ExecuteReader("GETBOMITEMS", currentProductSettings.Comments);
            //object[] obj = (object[])IR.Result;
            //if (IR.Success)
            //{
            //    SendFeedBack("GETBOMITEMS", true, obj[1]);
            //}

            WorkorderDB.GetActiveWorkOrder();
            if (WorkorderDB.ActiveOrder != null)
            {
                //WritePLCAndLogProcess(DialTablePLC, "E2232", 1, 1);
                int loadedcnt = 0;
                int.TryParse(WorkorderDB.ActiveOrder.Comments, out loadedcnt);
                WritePLCAndLogProcess(DialTablePLC, "E22000", 1, loadedcnt);
                WritePLCAndLogProcess(DialTablePLC, "E22608", 1, WorkorderDB.ActiveOrder.Pass);
                WritePLCAndLogProcess(DialTablePLC, "E22609", 1, WorkorderDB.ActiveOrder.Fail);
            }
            
            //St1Camera.ExecuteReader("SET_FILE", new object[] { currentProductSettings.St6ProgramNO.ToString() });

            //St6ECheck.ExecuteReader("LOADCANDLL", currentProductSettings.St6CanDll.ToString());
        }
        protected override void CycleProcess()
        {
            int n1 = Environment.TickCount;
            //Logger.Write("during the event manager's cycle process, the manager's hashcode is " + this.GetHashCode().ToString());
            base.CycleProcess();
            System.Threading.Thread.Sleep(10);

            if (cycleList.Count > 100)
            {
                cycleList.Clear();
            }
            cycleList.Add(System.DateTime.Now.Subtract(lastTime).TotalMilliseconds);
            lastTime = System.DateTime.Now;

            PLCCycleReset(DialTablePLC);
            try
            {
                ThreadMessage tmReceive = QuenueManager.GetQueue(ManagerName);
                if (tmReceive != null)
                {
                    MessagePreProcess(tmReceive);
                    MessageProcess(tmReceive);
                }
            }
            catch (Exception ex)
            {
                ExManager.HandleException(ex, "Policy");
            }
            this.RefreshUIItems(MyUIRefreshItems, false);
            this.HandleInformationList();
            this.AutoRun();
            n1 = Environment.TickCount - n1;
            int aa = 0;
        }

        private void HandleInformationList()
        {
            if (ErrorsChangeDetected())
            {
                SendFeedBack("ERROR_TAKE", true, new object[] { CurrentErrors, AllStnNestID });
            }
            if (ConditionsChangeDetected())
            {
                SendFeedBack("CONDITION_TAKE", true, CurrentConditions);
            }
            //CheckConnectStatusAndSetError(St1Printer, "0097");
            //CheckConnectStatusAndSetError(St1RejectScanner, "0098");
            //CheckConnectStatusAndSetError(St1Scanner, "0099");
            //CheckConnectStatusAndSetError(LaserMarker, "0673");
  
        }
        private void MessagePreProcess(ThreadMessage tmReceive)
        {
            switch (tmReceive.Command)
            {
                case "ACTIVATE_UI":
                    //TestAsyncFeedBackMessage();
                    {
                        string _PreUI = CurrentUI;
                        CurrentUI = tmReceive.Data.ToString();
                        MyUIRefreshItems = UserInterfaceDB.GetUIRefreshItems(CurrentUI);
                        Dictionary<string, StringValueList<UserInterfaceItem>> baseUIItems = UserInterfaceDB.GetUIRefreshItems("BaseUI");
                        foreach (KeyValuePair<string, StringValueList<UserInterfaceItem>> needAddItem in baseUIItems)
                        {
                            MyUIRefreshItems.Add(needAddItem.Key, needAddItem.Value);
                        }
                        RefreshUIItems(MyUIRefreshItems, true);
                        SendFeedBack("ERROR_TAKE", true, CurrentErrors);
                        SendFeedBack(tmReceive.Command, true, new string[] { CurrentUI, _PreUI });
                        SendFeedBack("CONDITION_TAKE", true, CurrentConditions);
                        SendFeedBack("ACTIVE_ORDER", true, null);
                    }
                    break;
                case "UI_ID":
                    this.stationIndex = (int)tmReceive.Data;
                    WritePLC(DialTablePLC, "E99", stationIndex.ToString());
                    break;
                case "UIITEM_ACTION":
                    {
                        UserInterfaceItem uiActionItem = tmReceive.Data as UserInterfaceItem;
                        ActionForUIItems(uiActionItem);
                        SendFeedBack(tmReceive.Command, true, CurrentUI);
                    }
                    break;
                case "UIITEM_ACTION_MOUSE_DOWN":
                    {
                        UserInterfaceItem uiActionItem = tmReceive.Data as UserInterfaceItem;
                        ActionForUIItemsMouseDown(uiActionItem);
                        SendFeedBack(tmReceive.Command, true, CurrentUI);
                    }
                    break;
                case "UIITEM_ACTION_MOUSE_UP":
                    {
                        UserInterfaceItem uiActionItem = tmReceive.Data as UserInterfaceItem;
                        ActionForUIItemsMouseUp(uiActionItem);
                        SendFeedBack(tmReceive.Command, true, CurrentUI);
                    }
                    break;    
                case "UIITEM_VALUE":
                    {
                        object[] dataRecvs = (object[])tmReceive.Data;

                        UserInterfaceItem uiActionItem = dataRecvs[0] as UserInterfaceItem;

                        ActionForUIItemsValue(uiActionItem, dataRecvs[1]);
                        SendFeedBack(tmReceive.Command, true, CurrentUI);
                    }
                    break;
                case "ACTIVE_ERROR":
                    WritePLC(DialTablePLC, "E2003", tmReceive.Data.ToString());
                    SendFeedBack(tmReceive.Command, true, null);
                    break;
                case "ASYNC_COMMAND_":
                    object[] parameters = tmReceive.Data as object[];
                    Action<object> action = parameters[0] as Action<object>;
                    action(parameters[1]);
                    break;

                #region st6 Robot maintenance
                case "ST6_ROBOTDRIVER_INIT":
                    {
                        St6Robot.ExecuteReader("INIT", new object[] { this, base.myConfig.St6RobotConfig });
                    }
                    break;
                case "ST6_ROBOTDRIVER_EXIT":
                    {
                        St6Robot.ExecuteReader("EXIT", null);
                    }
                    break;
                case "ST6_CONNECT_STATUS":
                    {
                        St6Robot.ExecuteReader("CONNECT_STATUS", null);
                    }
                    break;
                case "ST6_GET_SERVOSTATUS":
                    {
                        St6Robot.ExecuteReader("GET_SERVOSTATUS", null);
                    }
                    break;
                case "ST6_SET_SERVOSTATUS":
                    {
                        St6Robot.ExecuteReader("SET_SERVOSTATUS", tmReceive.Data);
                    }
                    break;
                case "ST6_GET_EMGSTATUS":
                    {
                        St6Robot.ExecuteReader("GET_EMGSTATUS", null);
                    }
                    break;
                case "ST6_RSET_EMGSTATUS":
                    {
                        St6Robot.ExecuteReader("RSET_EMGSTATUS", null);
                    }
                    break;
                case "ST6_GET_ALLNOTES":
                    {
                        St6Robot.ExecuteReader("GET_ALLNOTES", null);
                    }
                    break;
                case "ST6_GET_ASSIGNEDPOINTS":
                    {
                        St6Robot.ExecuteReader("GET_ASSIGNEDPOINTS", tmReceive.Data);
                    }
                    break;
                case "ST6_GET_ALLPOINTS":
                    {
                        St6Robot.ExecuteReader("GET_ALLPOINTS", null);
                    }
                    break;
                case "ST6_TEACH_POINT":
                    {
                        St6Robot.ExecuteReader("TEACH_POINT", tmReceive.Data);
                    }
                    break;
                case "ST6_SET_POINT":
                    {
                        St6Robot.ExecuteReader("WRITE_POINTS", tmReceive.Data);
                    }
                    break;
                case "ST6_GET_CURRENT":
                    {
                        St6Robot.ExecuteReader("GET_CURRENT", null);
                    }
                    break;
                case "ST6_CHANGE_RUNMODE":
                    {
                        St6Robot.ExecuteReader("CHANGE_RUNMODE", tmReceive.Data);
                    }
                    break;
                case "ST6_SET_UNIT":
                    {
                        St6Robot.ExecuteReader("SET_UNIT", null);
                    }
                    break;
                #endregion
            }
        }


        private void MessageProcess(ThreadMessage tmReceive)
        {
            switch (tmReceive.Command)
            {
                case "TRIAL_RUN":
                    {
                        bool bTrialRun = bool.Parse(tmReceive.Data.ToString());
                        WritePLC(DialTablePLC, "CIO106.1", bTrialRun.ToString());
                        if(bTrialRun)
                            WritePLC(DialTablePLC, "E2221.06", "False");
                    }
                    break;
                case "REWORK":
                    {
                        bool bRework = bool.Parse(tmReceive.Data.ToString());
                        WritePLC(DialTablePLC, "CIO106.2", bRework.ToString());
                    }
                    break;
                case "MODE_REQUEST":
                    WritePLC(DialTablePLC, "E2000." + tmReceive.Data.ToString(), "True");
                    System.Threading.Thread.Sleep(100);
                    WritePLC(DialTablePLC, "E2000." + tmReceive.Data.ToString(), "False");
                    break;
               
                case "EMPTY_LINE":
                    {
                        bool bEmpty = bool.Parse(tmReceive.Data.ToString());

                        WritePLC(DialTablePLC, "CIO106.0", bEmpty.ToString());
                    }
                    break;
                case "ECHECK_TRIGGER":
                    {
                        for (int i = 0; i < 3; i++)
                        {
                            Thread.Sleep(200);
                            Driver.IExecuteReader IR = St6ECheck.ExecuteReader("GETECUSN", null);
                            if (IR.Success)
                            {
                                object[] obj = (object[])IR.Result;
                                SendFeedBack("ECHECK_TRIGGER_RET", true, obj[1]);
                                break;
                            }
                            else
                            {
                                object[] obj = (object[])IR.Result;
                                SendFeedBack("ECHECK_TRIGGER_RET", true, "NO READ");
                                St6ECheck.ExecuteReader("EXIT", null);
                                St6ECheck.ExecuteReader("INIT", new object[] { this, base.myConfig.St6ECheckConfig });
                                St6ECheck.ExecuteReader("LOADCANDLL", currentProductSettings.St6CanDll.ToString());
                            }
                        }
                    }
                    break;
                case "NEST_CFG":
                    {
                        int nestcfg = int.Parse(tmReceive.Data.ToString());

                        WritePLC(DialTablePLC, "E2008", nestcfg.ToString());
                    }
                    break;
                case "STATION_CFG":
                    {
                        int nestcfg = int.Parse(tmReceive.Data.ToString());

                        WritePLC(DialTablePLC, "E2007", nestcfg.ToString());
                    }
                    break;
                case "ACTIVEMATERIAL":
                    {
                        Driver.IExecuteReader IR = St12Trace.ExecuteReader("ACTIVEMATERIAL", tmReceive.Data);
                        if (IR.Success && st1MaterialArray!=null)
                        {
                            object[] obj = (object[])IR.Result;
                            object[] ret = new object[2];
                            DataTable dt = (DataTable)obj[1];
                            
                            foreach (DataRow dr in dt.Rows)
                            {
                                foreach (DataRow drSt1 in st1MaterialArray.Rows)
                                {
                                    if (dr["partNo"].ToString()==drSt1["partNo"].ToString()
                                        && dr["sn"].ToString() != drSt1["sn"].ToString())
                                    {
                                        drSt1["sn"] = dr["sn"].ToString();
                                        drSt1["quantity"] = dr["quantity"];
                                    }
                                }
                            }
                            ret[0] = st1MaterialArray;
                            ret[1] = 3;
                            SendFeedBack("GETBOMITEMS", true, ret);
                            
                            if (st1MaterialArray!=null 
                                && st1MaterialArray.Rows.Count == 1 
                                && st1MaterialArray.Rows[0]["sn"].ToString() != "" 
                                //&& st1MaterialArray.Rows[1]["sn"].ToString() != ""
                                && int.Parse(st1MaterialArray.Rows[0]["quantity"].ToString()) > 0
                                //&& int.Parse(st1MaterialArray.Rows[1]["quantity"].ToString()) > 0
                                )
                                WritePLC(DialTablePLC, "E2221.6", "False");
                            bool tempFlag = true;
                            if (st1MaterialArray != null && st1MaterialArray.Rows.Count >1)
                            {
                                for (int i = 0; i < st1MaterialArray.Rows.Count; i++ )
                                {
                                    if (st1MaterialArray.Rows[0]["sn"].ToString() == ""
                                        || int.Parse(st1MaterialArray.Rows[i]["quantity"].ToString()) <= 0)
                                        tempFlag = false;
                                }
                            }
                            if (tempFlag)
                            {
                                WritePLC(DialTablePLC, "E2221.6", "False");
                            }
                        }
                        else
                        {
                            object[] obj = (object[])IR.Result;
                            object[] ret = new object[2];
                            ret[0] = null;
                            ret[1] = 4;
                            SendFeedBack("GETBOMITEMS", true, ret);
                            string str = "Itac 错误信息：" + obj[2].ToString();
                            //ShowMSG(str);
                            SendFeedBack("ASYNCMSG", true, str);
                        }
                    }
                    break;
                case "ACTIVATE_NEW_WORKORDER":
                    {
                        if (bTrialRun)
                            break;
                        Driver.IExecuteReader IR = St12Trace.ExecuteReader("CHECK_CONNECTION", "NOTHING");
                        if (!IR.Success)
                        {
                            //ShowMSG("ITAC连接断开，请检查！");
                            SendFeedBack("CHECK_CONNECTION", true, null);
                            break;
                        }
                        IR = St12Trace.ExecuteReader("GETBOMITEMS", tmReceive.Data.ToString());
                        object[] obj = (object[])IR.Result;
                        object[] ret = new object[2];
                        if (IR.Success)
                        {
                            st1MaterialArray = (DataTable)obj[1];
                            ret[0] = obj[1];
                            ret[1] = 1;
                            SendFeedBack("GETBOMITEMS", true, ret);
                            WritePLC(DialTablePLC, "E2221.06", "True");
                            //SendFeedBack("ACTIVATE_NEW_WORKORDER_RET", true, null);
                        }
                        else
                        {
                            ret[0] = null;
                            ret[1] = 2;
                            SendFeedBack("GETBOMITEMS", true, ret);
                        }
                    }
                    break;
                case "PRINT_TEMP_NR":
                    {
                        Driver.IExecuteReader IR = St12Trace.ExecuteReader("PRINT_TEMP_NR", tmReceive.Data, currentProductSettings.St8DispathPrinterFile);
                        if (!IR.Success)
                        {
                            //ShowMSG("打印临时箱号失败！")
                            SendFeedBack("ASYNCMSG", true, "打印临时箱号失败！"); 
                        }
                    }
                    break;
                case "REPRINT":
                    {
                        Driver.IExecuteReader IR = St12Trace.ExecuteReader("PRINT_TEMP_NR", tmReceive.Data, currentProductSettings.St8DispathPrinterFile);
                        if (!IR.Success)
                        {
                            //ShowMSG("重新打印箱号失败！");
                            SendFeedBack("ASYNCMSG", true, "重新打印箱号失败！"); 
                        }
                    }
                    break;
                case "ASSEMBLY":
                    {
                        Driver.IExecuteReader IR = St12Trace.ExecuteReader("PRINT_TEMP_NR", tmReceive.Data);
                        if (!IR.Success)
                        {
                            //ShowMSG("拼箱失败！");
                            SendFeedBack("ASYNCMSG", true, "拼箱失败！");
                        }
                    }
                    break;
            }
            this.MessageProduct(tmReceive);
        }
        private ProductSettings currentProductSettings = null;
        private void MessageProduct(ThreadMessage tmReceive)
        {
            switch (tmReceive.Command)
            {
                case "REACTIVE_PRODUCT":
                    {
                        WorkorderDB.GetActiveWorkOrder();
                        ProductSettings s1 = WorkorderDB.ActiveProduct;
                        if (s1 != null)
                            currentProductSettings = s1;
                        WritePLCAndLogProcess(DialTablePLC, "E22000", 1, 0);
                        WritePLCAndLogProcess(DialTablePLC, "E22608", 1, 0);
                        WritePLCAndLogProcess(DialTablePLC, "E22609", 1, 0);
                    }
                    break;
                case "ACTIVE_ORDER":
                    WorkorderDB.GetActiveWorkOrder();
                    ProductSettings s = WorkorderDB.ActiveProduct;
                    if (s != null)
                        currentProductSettings = s;
                    //DoingThingsHere
                    try
                    {
                        Driver.IExecuteReader IR = St12Trace.ExecuteReader("DEACTIVATE_WORKORDER", null);
                        if (IR.Success)
                        {
                            object[] ret = new object[2];
                            ret[0] = null;
                            ret[1] = 0;
                            SendFeedBack("GETBOMITEMS", true, ret);
                        }
                        //todo compare product no from ITAC
                        ////
                        ////
                        WritePLC(DialTablePLC, "CIO106.1", "False"); //  tryrun
                        WritePLC(DialTablePLC, "CIO106.2", "False"); //  rework
                        SendFeedBack("REPORT_WORKORDER_DOWNLOAD", true, "DownLoad for station settings");
                        Thread.Sleep(100);

                        #region St1
                        WritePLCAndLogProcess(DialTablePLC, "E22100", 1, currentProductSettings.St1NestID);
                        WritePLC(DialTablePLC, "E22140.0", currentProductSettings.St1HousingCheckEnable ? "False" : "True");
                        WritePLC(DialTablePLC, "E22140.1", currentProductSettings.St1ConnectorCheckEnable ? "False" : "True");
                        WritePLC(DialTablePLC, "E22140.2", currentProductSettings.St1CameraEnable ? "False" : "True");
                        WritePLC(DialTablePLC, "E22121.4", currentProductSettings.St1UseForntSensor ? "False" : "True");
                        WritePLC(DialTablePLC, "CIO105.15", currentProductSettings.St1PressMode ? "True" : "False");

                        if (currentProductSettings.St1PressMode)
                        {
                            currentProductSettings.St3Enable = false;
                        }
                        #endregion

                        #region St2
                        WritePLCAndLogProcess(DialTablePLC, "E22201", 1, currentProductSettings.St2ProgramID);
                        WritePLCAndLogProcess(DialTablePLC, "E22200", 1, currentProductSettings.St2ToolingID);
                        #endregion

                        #region St3
                        WritePLCAndLogProcess(DialTablePLC, "E22300", 1, currentProductSettings.St3LeftToolingID);
                        WritePLCAndLogProcess(DialTablePLC, "E22301", 1, currentProductSettings.St3RightToolingID);
                        WritePLC(DialTablePLC, "E22340", 18, currentProductSettings.St3SettingsToPLCWords());
                        #endregion

                        #region St4
                        WritePLCAndLogProcess(DialTablePLC, "E22401", 1, currentProductSettings.St4ProgramID);
                        WritePLCAndLogProcess(DialTablePLC, "E22400", 1, currentProductSettings.St4ToolingID);
                        #endregion

                        #region St5
                        WritePLCAndLogProcess(DialTablePLC, "E22500", 1, int.Parse(currentProductSettings.St5ProgramNO));
                        WritePLCAndLogProcess(DialTablePLC, "E22501", 1, int.Parse(currentProductSettings.St5ProductCheckProgramNO));
                        WritePLC(DialTablePLC, "E22573.0", !currentProductSettings.St5Enable1 ? "False" : "True");
                        WritePLC(DialTablePLC, "E22573.1", !currentProductSettings.St5Enable2 ? "False" : "True");
                        WritePLC(DialTablePLC, "E22573.2", !currentProductSettings.St5Enable3 ? "False" : "True");
                        WritePLC(DialTablePLC, "E22573.3", !currentProductSettings.St5Enable4 ? "False" : "True");
                        WritePLC(DialTablePLC, "E22573.4", !currentProductSettings.St5Enable5 ? "False" : "True");

                        int[] St5Pos = currentProductSettings.St5SettingsToPLCWords();
                        WritePLCAndLogProcess(DialTablePLC, "E22540", 2, new int[] { St5Pos[0], St5Pos[1] });
                        WritePLCAndLogProcess(DialTablePLC, "E22550", 2, new int[] { St5Pos[2], St5Pos[3] });
                        WritePLCAndLogProcess(DialTablePLC, "E22560", 2, new int[] { St5Pos[4], St5Pos[5] });
                        WritePLCAndLogProcess(DialTablePLC, "E22542", 2, new int[] { St5Pos[6], St5Pos[7] });
                        WritePLCAndLogProcess(DialTablePLC, "E22552", 2, new int[] { St5Pos[8], St5Pos[9] });
                        WritePLCAndLogProcess(DialTablePLC, "E22562", 2, new int[] { St5Pos[10], St5Pos[11] });
                        WritePLCAndLogProcess(DialTablePLC, "E22544", 2, new int[] { St5Pos[12], St5Pos[13] });
                        WritePLCAndLogProcess(DialTablePLC, "E22554", 2, new int[] { St5Pos[14], St5Pos[15] });
                        WritePLCAndLogProcess(DialTablePLC, "E22564", 2, new int[] { St5Pos[16], St5Pos[17] });
                        WritePLCAndLogProcess(DialTablePLC, "E22546", 2, new int[] { St5Pos[18], St5Pos[19] });
                        WritePLCAndLogProcess(DialTablePLC, "E22556", 2, new int[] { St5Pos[20], St5Pos[21] });
                        WritePLCAndLogProcess(DialTablePLC, "E22566", 2, new int[] { St5Pos[22], St5Pos[23] });
                        WritePLCAndLogProcess(DialTablePLC, "E22548", 2, new int[] { St5Pos[24], St5Pos[25] });
                        WritePLCAndLogProcess(DialTablePLC, "E22558", 2, new int[] { St5Pos[26], St5Pos[27] });
                        WritePLCAndLogProcess(DialTablePLC, "E22568", 2, new int[] { St5Pos[28], St5Pos[29] });
                        #endregion

                        #region St6
                        WritePLCAndLogProcess(DialTablePLC, "E22602", 1, currentProductSettings.St6ECheckToolingID);
                        WritePLCAndLogProcess(DialTablePLC, "E22600", 1, currentProductSettings.St6LeftGripperToolingID);
                        WritePLCAndLogProcess(DialTablePLC, "E22601", 1, currentProductSettings.St6RightGripperToolingID);
                        WritePLCAndLogProcess(DialTablePLC, "E22604", 1, currentProductSettings.St6PositionJobID);
                        St6ECheck.ExecuteReader("LOADCANDLL", currentProductSettings.St6CanDll.ToString());
                        #endregion

                        int stEnabled = 0;
                        if (currentProductSettings.St1Enable)
                        {
                            stEnabled |= (1 << 0);
                        }

                        if (currentProductSettings.St2Enable)
                        {
                            stEnabled |= (1 << 1);
                        }

                        if (currentProductSettings.St3Enable)
                        {
                            stEnabled |= (1 << 2);
                        }

                        if (currentProductSettings.St4Enable)
                        {
                            stEnabled |= (1 << 3);
                        }

                        if (currentProductSettings.St5Enable)
                        {
                            stEnabled |= (1 << 4);
                        }

                        if (currentProductSettings.St6Enable)
                        {
                            stEnabled |= (1 << 5);
                        }

                        WritePLCAndLogProcess(DialTablePLC, "E2232", 1, stEnabled);
                        WritePLCAndLogProcess(DialTablePLC, "E2007", 1, ~stEnabled & 0xFFFF);

                        if (WorkorderDB.ActiveOrder != null)
                        {
                            //WritePLCAndLogProcess(DialTablePLC, "E2232", 1, 1);
                            int loadedcnt = 0;
                            int.TryParse(WorkorderDB.ActiveOrder.Comments, out loadedcnt);
                            WritePLCAndLogProcess(DialTablePLC, "E22000", 1, loadedcnt);
                            WritePLCAndLogProcess(DialTablePLC, "E22608", 1, WorkorderDB.ActiveOrder.Pass);
                            WritePLCAndLogProcess(DialTablePLC, "E22609", 1, WorkorderDB.ActiveOrder.Fail);
                        }

                        //相机模板检测
                        if (tmReceive.Data == null)
                        {
                            SendFeedBack("PRODUCTCHECK", true, null);
                        }

                    }
                    catch (Exception ex)
                    {
                        SendFeedBack(tmReceive.Command, false, null);
                        throw ex;
                    }
                    SendFeedBack(tmReceive.Command, true, null);
                    break;
                case "TOOLING_CHECK":
                    Dictionary<string, string> checkItem = tmReceive.Data as Dictionary<string, string>;
                    string[] keys = checkItem.Keys.ToArray();
                    for (int i = 0; i < checkItem.Count; i++)
                    {
                        string addr = keys[i];
                        checkItem[addr] = ReadPLC<int>(DialTablePLC, addr).ToString();
                    }
                    SendFeedBack(tmReceive.Command, true, checkItem);
                    break;
                case "GET_STATION5_TEACHPANEL"://added today.
                    {
                        int[] teachPosition = ReadPLC<int[]>(DialTablePLC, "E12533", 30);
                        SendFeedBack(tmReceive.Command, true, teachPosition);
                    }
                    break;
                case "WRITE_ST3_PROGRAM":
                    WritePLC(DialTablePLC, "E22340", 18, (int[])tmReceive.Data);
                    break;
                case "GET_STATION4_TEACHPANEL"://added today.
                    {
                        int[] teachPosition = ReadPLC<int[]>(DialTablePLC, "E22340", 18);
                        SendFeedBack(tmReceive.Command, true, teachPosition);
                    }
                    break;
                case "WRITE_ST5_PROGRAM"://added today.
                    {
                        int[] St5Pos = (int[])tmReceive.Data;
                        WritePLCAndLogProcess(DialTablePLC, "E22540", 2, new int[] { St5Pos[0], St5Pos[1] });
                        WritePLCAndLogProcess(DialTablePLC, "E22550", 2, new int[] { St5Pos[2], St5Pos[3] });
                        WritePLCAndLogProcess(DialTablePLC, "E22560", 2, new int[] { St5Pos[4], St5Pos[5] });
                        WritePLCAndLogProcess(DialTablePLC, "E22542", 2, new int[] { St5Pos[6], St5Pos[7] });
                        WritePLCAndLogProcess(DialTablePLC, "E22552", 2, new int[] { St5Pos[8], St5Pos[9] });
                        WritePLCAndLogProcess(DialTablePLC, "E22562", 2, new int[] { St5Pos[10], St5Pos[11] });
                        WritePLCAndLogProcess(DialTablePLC, "E22544", 2, new int[] { St5Pos[12], St5Pos[13] });
                        WritePLCAndLogProcess(DialTablePLC, "E22554", 2, new int[] { St5Pos[14], St5Pos[15] });
                        WritePLCAndLogProcess(DialTablePLC, "E22564", 2, new int[] { St5Pos[16], St5Pos[17] });
                        WritePLCAndLogProcess(DialTablePLC, "E22546", 2, new int[] { St5Pos[18], St5Pos[19] });
                        WritePLCAndLogProcess(DialTablePLC, "E22556", 2, new int[] { St5Pos[20], St5Pos[21] });
                        WritePLCAndLogProcess(DialTablePLC, "E22566", 2, new int[] { St5Pos[22], St5Pos[23] });
                        WritePLCAndLogProcess(DialTablePLC, "E22548", 2, new int[] { St5Pos[24], St5Pos[25] });
                        WritePLCAndLogProcess(DialTablePLC, "E22558", 2, new int[] { St5Pos[26], St5Pos[27] });
                        WritePLCAndLogProcess(DialTablePLC, "E22568", 2, new int[] { St5Pos[28], St5Pos[29] });
                    }
                    break;
                case "SET_POINT":
                    WritePLC(DialTablePLC, tmReceive.Data.ToString(), "True");
                    break;
                case "RESET_POINT":
                    WritePLC(DialTablePLC, tmReceive.Data.ToString(), "False");
                    break;
                case "GET_STATION5_XYZ":
                    {
                        int[] teachPosition = ReadPLC<int[]>(DialTablePLC, "E12533", 30);
                        SendFeedBack(tmReceive.Command, true, teachPosition);
                    }
                    break;
                case "GET_STATION4_XYZ":
                    {
                        int[] teachPosition = ReadPLC<int[]>(DialTablePLC, "E12333", 40);
                        SendFeedBack(tmReceive.Command, true, teachPosition);
                    }
                    break;

                //相机模板测试
                case "PRODUCTCHECK":
                    {
                        string recipe = WorkorderDB.ActiveProduct.Name;

                        //bool bb = bool.Parse(tmReceive.Data.ToString());
                        if (recipe != current_recipe)
                        {
                            
                            bStn5ProductCheckResultOK = !currentProductSettings.St5ProductCheckEnable;
                            bStn5ProductCheckResultNG = bStn5ProductCheckResultOK;

                            current_recipe = recipe;
                            bProductCheck = !(bStn5ProductCheckResultOK && bStn5ProductCheckResultNG);
                            bLastProductCheck = bProductCheck;

                            if (bProductCheck)
                            {
                                int stEnabled = 0;
                                stEnabled |= 1 << 0;
                                stEnabled |= 1 << 4;
                                stEnabled = ~stEnabled;
                                WritePLC(DialTablePLC, "CIO106.1", "True"); //  TRYRAN
                                WritePLC(DialTablePLC, "CIO106.2", "True"); //  rework
                                WritePLC(DialTablePLC, "E23203.0","True"); //  productchck
                                Thread.Sleep(500);
                                WritePLC(DialTablePLC, "E2007", (stEnabled & 0xFFFF).ToString());
                            }
                        }
                        else
                        {
                            bProductCheck = false;
                            bLastProductCheck = bProductCheck;
                            WritePLC(DialTablePLC, "CIO106.1", "False"); //  TRYRAN
                            WritePLC(DialTablePLC, "CIO106.2", "False"); //  rework
                            WritePLC(DialTablePLC, "E23203.0", "False"); //  productchck
                        }

                        if(bProductCheck)
                        {
                            SendFeedBack("ASYNCMSG", true, "开始相机模板检测。");
                        }
                    }
                    break;
            }
        }

        private void AutoRun()
        {
            try
            {
                bool bb = base.ReadPLC<bool>(DialTablePLC, "CIO8.00", 1);
                if (bb)
                    SendFeedBack("ACTIVE_MAINUI", true, null);

                //AutoRunDeviceTemplate("s", "s", "s", "s");
                //this.RefreshStationRelated();
                bool testBool = base.ReadPLC<bool>(DialTablePLC, "CIO100.1", 1);


                testBool =  base.ReadPLC<bool>(DialTablePLC, "CIO106.0", 1);
                if (testBool != bEmptyLine)
                {
                    bEmptyLine = testBool;
                    SendFeedBack("EMPTY_LINE", true, bEmptyLine);
                }

                testBool = base.ReadPLC<bool>(DialTablePLC, "CIO106.1", 1);
                if (testBool != bTrialRun)
                {
                    bTrialRun = testBool;
                    SendFeedBack("TRIAL_RUN", bProductCheck, bTrialRun);
                }

                testBool = base.ReadPLC<bool>(DialTablePLC, "CIO106.2", 1);
                if (testBool != bRework)
                {
                    bRework = testBool;
                    SendFeedBack("REWORK", bProductCheck, bRework);
                }

                //if (bProductCheck)
                //{
                //    bProductCheck = !(bStn5ProductCheckResultOK && bStn5ProductCheckResultNG);
                //    SendFeedBack("PRODUCTCHECK_STATUS", true, new bool[] { bStn5ProductCheckResultOK, bStn5ProductCheckResultNG });
                //}

                //if (!bProductCheck && bLastProductCheck)
                //{
                //    bLastProductCheck = false;
                //    SendFeedBack("ASYNCMSG", true, "模板检测完成。请重新激活工单，开始自动生产。");
                //    SendFeedBack("PRODUCTCHECK_STATUS", false, null);
                //}

                WritePLC(DialTablePLC, "E23203.0", bProductCheck ? "True" : "False"); //  rework

//                 #region  st6Camera
//                 if (bStartTrigSt1Camera)
//                 {
//                     Driver.IExecuteReader IR = St1Camera.ExecuteReader("TRIGGER_STATUS", null);
//                     if (IR.Success)
//                     {
//                         if (bool.Parse(IR.Result.ToString()))
//                         {
//                             //todo
//                             bool passorfail = bool.Parse(IR.Result.ToString());
//                             SendFeedBack("START_CAMERA", true, new int[] { 2, passorfail ? 1 : 2, 1 });//{a,b}: a=1 is busy, a=2 is finish; b= fault code
//                             bStartTrigSt1Camera = false;
//                         }
//                     }
//                 }
//                 #endregion
                if (currentProductSettings == null) return;

                AutoRunSt1("E22120.04");

                this.AutoRunSt1HousingScanner("E22120.0", "E22120.2", "E22121.0", "E22130");//Housing

                this.AutoRunSt1ConnecterScanner("E22120.1", "E22120.3", "E22121.1", "E22131");//Connectting

                this.AutoRunSt1Camera("E22122.0", "E22122.1", "E22122.2", "E22123");

                //this.AutoRunSt5Camera("E23203.2", "E23203.3", "E23203.1", "E23203.4");

                this.AutoRunSt6ECheck("E22680.0", "E22680.1", "E22680.8", "E22681");

                this.AutoRunSt8UploadState("E22685.0", "E22685.1", "E22685.2", "E22686");
            }
            catch (Exception ex)
            {
                ExManager.HandleException(ex, "Policy");
            }
        }

        private int stationIndex = 0;
        private string currentStationSn = string.Empty;
        private string currentStationSn1 = string.Empty;
        private void RefreshStationRelated()
        {
            string address = "D" + (7005 + (stationIndex - 1) * 300).ToString();
            int[] intSn = ReadPLC<int[]>(DialTablePLC, address, 11);
            string sn = PLCWordsToString(intSn);
            sn = sn.Replace("\0", string.Empty);

            address = "E105";
            int[] intSnManual = ReadPLC<int[]>(DialTablePLC, address, 11);
            string sn1 = PLCWordsToString(intSnManual);
            sn1 = sn1.Replace("\0", string.Empty);
            if ((currentStationSn != sn) || (currentStationSn1 != sn1))
            {
                SendFeedBack("STATION_RELATED", true, new string[] { sn, sn1 });
                currentStationSn1 = sn1;
                currentStationSn = sn;
            }
            
        }

        private string GetSn(int stationIndex )
        {
            string address = "D" + (7005 + (stationIndex - 1) * 300).ToString();
            int[] intSn = ReadPLC<int[]>(DialTablePLC, address, 12);
            string sn = PLCWordsToString(intSn);
            sn = sn.Replace("\0", string.Empty);
            sn = sn.Trim();
            //sn = sn.Substring(0, snHousingLength);
            return sn;
        }

        private string GetCustomerSn(int stationIndex)
        {
            string address = "D" + (7034 + (stationIndex - 1) * 300).ToString();
            int[] intSn = ReadPLC<int[]>(DialTablePLC, address, 15);
            string sn = PLCWordsToString(intSn);
            sn = sn.Replace("\0", string.Empty);
            sn = sn.Trim();
            return sn;
        }

        private void WriteStringToPLC(string addr, string text)
        {
            Byte[] baT = Encoding.ASCII.GetBytes(text);
            Byte[] baT2 = null;
            int[] iaT = null;
            BytesArrayTo2BytesArray(baT, out baT2);
            BytesArrayToIntArray(baT2, out iaT);
            WritePLC(DialTablePLC, addr, iaT.Length, iaT);
        }

        private void AutoRunSt1(string start)
        {
            if (DetectRisingEdge(DialTablePLC, start))
            {
                if (bTrialRun)
                {
                    WritePLC(DialTablePLC, "E22121.7", "True");
                    return;
                }
                bool testBool = base.ReadPLC<bool>(DialTablePLC, "E22121.6", 1);
                if (testBool)
                {
                    WritePLC(DialTablePLC, "E22121.8", "True");
                    //ShowMSG("请扫描物料！！！");
                    SendFeedBack("ASYNCMSG", true, "请扫描物料！！！");
                    return;
                }
                if (st1MaterialArray == null
                    || st1MaterialArray.Rows.Count < 1)
                {
                    WritePLC(DialTablePLC, "E22121.8", "True");
                    WritePLC(DialTablePLC, "E22121.6", "True");
                    string str = "请扫描物料!!!";
                    //ShowMSG(str);
                    SendFeedBack("ASYNCMSG", true, str);
                    return;
                }
                for (int i = 0; i < st1MaterialArray.Rows.Count;i++ )
                {
                    if (st1MaterialArray.Rows[i]["sn"].ToString() == ""
                    || int.Parse(st1MaterialArray.Rows[i]["quantity"].ToString()) <= 0)
                    {
                        WritePLC(DialTablePLC, "E22121.8", "True");
                        WritePLC(DialTablePLC, "E22121.6", "True");
                        string str = "请扫描物料：" + st1MaterialArray.Rows[0]["compName"].ToString() + "-" + st1MaterialArray.Rows[0]["partNo"].ToString();
                        //ShowMSG(str);
                        SendFeedBack("ASYNCMSG", true, str);
                        return;
                    }
                }

                //WriteStringToPLC("D7110", st1MaterialArray.Rows[0]["sn"].ToString().Substring(8, 16));
                
                WritePLC(DialTablePLC, "E22121.7", "True");
                for (int i = 0; i < st1MaterialArray.Rows.Count; i++)
                {
                    st1MaterialArray.Rows[i]["quantity"] = int.Parse(st1MaterialArray.Rows[i]["quantity"].ToString()) - int.Parse(st1MaterialArray.Rows[i]["useAmount"].ToString());
                }
                //st1MaterialArray.Rows[0]["quantity"] = int.Parse(st1MaterialArray.Rows[0]["quantity"].ToString()) - int.Parse(st1MaterialArray.Rows[0]["useAmount"].ToString());
                //if (st1MaterialArray.Rows.Count ==2)
                //{
                //    //WriteStringToPLC("D7134", st1MaterialArray.Rows[1]["sn"].ToString().Substring(8, 16));
                //    st1MaterialArray.Rows[1]["quantity"] = int.Parse(st1MaterialArray.Rows[1]["quantity"].ToString()) - int.Parse(st1MaterialArray.Rows[1]["useAmount"].ToString());
                //}
                object[] ret = { st1MaterialArray, 0 };
                SendFeedBack("GETBOMITEMS", true, ret);

                WritePLC(DialTablePLC, "E22101.7", "True");
                int nestID = base.ReadPLC<int>(DialTablePLC, "E2800", 1);
                ItacDB.Delete(nestID);
                for (int i = 0; i < st1MaterialArray.Rows.Count; i++)
                {
                    //update material in db
                    ItacDB.Add(nestID, st1MaterialArray.Rows[i]["sn"].ToString());
                }
            }
            return;
        }

        bool st1Start_Camera = false;
        int st1CameraStatus = 0;    //0:空闲，1：忙，2：OK，3：NG，4：Error&TimeOut
        int st1StatusShowTime = 0;
        private void AutoRunSt1Camera(string reset, string start, string ready, string result)
        {
            bool startValue = ReadPLC<bool>(DialTablePLC, start);

            if (DetectRisingEdge(DialTablePLC, start))
            {
                Driver.IExecuteReader IR = St1Camera.ExecuteReader("GET_FILENAME", null);

                if (IR.Success)
                {
                    if (IR.Result.ToString().ToUpper() != currentProductSettings.St1CameraJob.ToUpper())
                    {
                        St1Camera.ExecuteReader("OFFLINE", null);
                        St1Camera.ExecuteReader("SET_FILE", new object[] { currentProductSettings.St1CameraJob });
                        St1Camera.ExecuteReader("ONLINE", null);
                    }
                }

                WritePLC(DialTablePLC, result, "5");//=5 means onging the process

                if (DriverConnectStatus(St1Camera))
                {
                    WritePLC(DialTablePLC, ready, "False");     //ready 
                    St1Camera.ExecuteReader("TRIGGER", null);
                    st1Start_Camera = true;

                    st1CameraStatus = 1;
                    st1StatusShowTime = Environment.TickCount & Int32.MaxValue;
                    SendFeedBack("REFRESH_CAMERASTATUS", true, new object[] { "STN1", st1CameraStatus });
                }
                else
                {
                    WritePLC(DialTablePLC, result, "11");  //connection lost
                    WritePLC(DialTablePLC, ready, "False");  //ready 

                    st1CameraStatus = 4;
                    st1StatusShowTime = Environment.TickCount & Int32.MaxValue;
                    SendFeedBack("REFRESH_CAMERASTATUS", true, new object[] { "STN1", st1CameraStatus });
                }
            }

            if (st1Start_Camera)
            {
                if (DriverConnectStatus(St1Camera))
                {
                    Driver.IExecuteReader IR = St1Camera.ExecuteReader("TRIGGER_RESULT");

                    if (IR.Success)
                    {
                        st1Start_Camera = false;

                        if (IR.Result.ToString() == "OK")
                        {
                            
                            WritePLC(DialTablePLC, result, "1"); //ready
                            WritePLC(DialTablePLC, ready, "True");

                            st1CameraStatus = 2;
                            st1StatusShowTime = Environment.TickCount & Int32.MaxValue;
                            SendFeedBack("REFRESH_CAMERASTATUS", true, new object[] { "STN1", st1CameraStatus });
                        }
                        else
                        {
                            
                            WritePLC(DialTablePLC, result, "13"); //read 2d error
                            WritePLC(DialTablePLC, ready, "True");
                           
                            st1CameraStatus = 3;
                            st1StatusShowTime = Environment.TickCount & Int32.MaxValue;
                            SendFeedBack("REFRESH_CAMERASTATUS", true, new object[] { "STN1", st1CameraStatus });
                        }
                    }
                }
                else
                {
                    WritePLC(DialTablePLC, result, "11");  //error code 2 for station 1 ,start failed caused by connection lost
                    WritePLC(DialTablePLC, ready, "False");                              //ready 
                    st1Start_Camera = false;
                }
            }

            if (DetectRisingEdge(DialTablePLC, reset))
            {
                st1Start_Camera = false;
                St1Camera.ExecuteReader("EXIT", null);
                St1Camera.ExecuteReader("INIT", new object[] { this, base.myConfig.St1CameraConfig });

                if (DriverConnectStatus(St1Camera))
                {
                    WritePLC(DialTablePLC, result, "1");//reset success
                    WritePLC(DialTablePLC, ready, "True");
                }
                else
                {
                    WritePLC(DialTablePLC, result, "12");//error code 1 for station 1 ,reset failed
                    WritePLC(DialTablePLC, ready, "False");
                }
            }

            if (st1CameraStatus > 0)
            {
                int intTickCount = Environment.TickCount & Int32.MaxValue;
                int intTimeTaken = intTickCount < st1StatusShowTime ? Int32.MaxValue - st1StatusShowTime + intTickCount : intTickCount - st1StatusShowTime;

                if (intTimeTaken > 3000)
                {
                    st1CameraStatus = 0;
                    SendFeedBack("REFRESH_CAMERASTATUS", true, new object[] { "STN1", st1CameraStatus });
                }
            }
        }

        bool start_St1HousingScanner = false;
        int rp200 = 0;
        private void AutoRunSt1HousingScanner(string reset, string start, string ready, string result)
        {
            long ttt = Environment.TickCount;
            bool startValue = ReadPLC<bool>(DialTablePLC, start);
            if (DetectRisingEdge(DialTablePLC, start))
            {


                WritePLC(DialTablePLC, result, "5");//=5 means onging the process
                WritePLC(DialTablePLC, ready, "False"); 
       
                if (DriverConnectStatus(St1HousingScanner))
                {
                    WritePLC(DialTablePLC, result, "5");//=5 means onging the process
                    WritePLC(DialTablePLC, ready, "False");                                //ready 
                    St1HousingScanner.ExecuteReader("TRIGGERON", null);
                    start_St1HousingScanner = true;
                    rp200 = 1;
                }
                else
                {
                    WritePLC(DialTablePLC, result, "12");  //error code 2 for station 1 start failed caused by connection lost
                    WritePLC(DialTablePLC, ready, "False");                              //ready 
                    start_St1HousingScanner = false;
                }
            }
            if (start_St1HousingScanner)
            {
                if (DriverConnectStatus(St1HousingScanner))
                {
                    //Thread.Sleep(2000);
                    Driver.IExecuteReader IR = St1HousingScanner.ExecuteReader("READ", null);
                    if (IR.Success)
                    {
                        string snHousing = IR.Result.ToString().Trim('\0');
                        if (currentProductSettings.St1HousingCheckEnable)
                        {
                            rp200 += 1;
                            if (snHousing.Contains("NOREAD") || snHousing.Length == 0 )
                            {
                                if (rp200 == 2)
                                {
                                    St1HousingScanner.ExecuteReader("TRIGGERON", null);
                                    start_St1HousingScanner = true;
                                    return;
                                }
                                WritePLC(DialTablePLC, result, "11"); //read barcode error
                                WritePLC(DialTablePLC, ready, "True");
                                start_St1HousingScanner = false;
                                return;
                            }
                            if (!snHousing.Contains(currentProductSettings.St1HousingSNRequirement.ToString()))
                            {
                                WritePLC(DialTablePLC, result, "13"); //barcode not match
                                WritePLC(DialTablePLC, ready, "True");
                                start_St1HousingScanner = false;
                                return;
                            }
                            
                            //HousingSN保存
                            int nestID = base.ReadPLC<int>(DialTablePLC, "E2800", 1);
                            HousingDB.Delete(nestID);
                            HousingDB.Add(nestID, snHousing);

                            if (currentProductSettings.St1CheckHousingAssemblySN)
                            {
                                Driver.IExecuteReader IR1 = St12Trace.ExecuteReader("GETHOUSINGASSEMBLYSN", snHousing);

                                if (IR1.Success)
                                {
                                    bool bMatched = false;

                                    foreach (DataRow data in st1MaterialArray.Rows)
                                    {
                                        if (data["partNo"].ToString() == IR1.Result.ToString())
                                        {
                                            bMatched = true;
                                            break;
                                        }
                                    }

                                    if (!bMatched)
                                    {
                                        WritePLC(DialTablePLC, result, "14"); // 物料不匹配
                                        WritePLC(DialTablePLC, ready, "True");
                                        start_St1HousingScanner = false;
                                        return;
                                    }
                                }
                                else
                                {
                                    WritePLC(DialTablePLC, result, "15"); // get housing assembly sn fail
                                    WritePLC(DialTablePLC, ready, "True");
                                    start_St1HousingScanner = false;
                                    return;
                                }
                            }

                            //Byte[] baT = Encoding.ASCII.GetBytes(snHousing);
                            //Byte[] baT2 = null;
                            //int[] iaT = null;
                            //BytesArrayTo2BytesArray(baT, out baT2);
                            //BytesArrayToIntArray(baT2, out iaT);
                            //WritePLC(DialTablePLC, "D7105", iaT.Length, iaT);

                            WritePLC(DialTablePLC, result, "1"); //ready
                            WritePLC(DialTablePLC, ready, "True");
                            start_St1HousingScanner = false;
                        }
                        else
                        {
                            WritePLC(DialTablePLC, result, "1"); //ready
                            WritePLC(DialTablePLC, ready, "True");
                            start_St1HousingScanner = false;
                        }
                    }
                    //else
                    //{
                    //    St1HousingScanner.ExecuteReader("TRIGGEROFF", null);
                    //    rp200 += 1;
                    //    if (rp200 == 2)
                    //    {
                    //        St1HousingScanner.ExecuteReader("TRIGGERON", null);
                    //        start_St1HousingScanner = true;
                    //        return;
                    //    }
                    //    WritePLC(DialTablePLC, result, "11"); //read barcode error
                    //    WritePLC(DialTablePLC, ready, "True");
                    //    start_St1HousingScanner = false;
                    //}
                }
                else
                {
                    WritePLC(DialTablePLC, result, "12");  //connection lost
                    WritePLC(DialTablePLC, ready, "False");
                    start_St1HousingScanner = false;
                }
            }
            if (DetectRisingEdge(DialTablePLC, reset))
            {
                start_St1HousingScanner = false;

                try
                {
                    St1HousingScanner.ExecuteReader("EXIT", null);
                    St1HousingScanner.ExecuteReader("INIT", new object[] { this, base.myConfig.St1HousingScannerConfig });
                    if (DriverConnectStatus(St1HousingScanner))
                    {
                        WritePLC(DialTablePLC, result, "0");//reset success
                        WritePLC(DialTablePLC, ready, "True");
                    }
                    else
                    {
                        WritePLC(DialTablePLC, result, "12");//error code 1 for station 1 ,reset failed
                        WritePLC(DialTablePLC, ready, "False");
                    }
                }
                catch
                {
                    WritePLC(DialTablePLC, result, "12");//error code 1 for station 1 ,reset failed
                    WritePLC(DialTablePLC, ready, "False");
                }
            }
        }

        bool start_St1ConnecterScanner = false;
        int rp300 = 0;
        private void AutoRunSt1ConnecterScanner(string reset, string start, string ready, string result)
        {
            long ttt = Environment.TickCount;
            bool startValue = ReadPLC<bool>(DialTablePLC, start);
            if (DetectRisingEdge(DialTablePLC, start))
            {

                WritePLC(DialTablePLC, result, "5");//=5 means onging the process
                WritePLC(DialTablePLC, ready, "False"); 

                if (DriverConnectStatus(St1ConnecterScanner))
                {
                    WritePLC(DialTablePLC, ready, "False");                                //ready 
                    St1ConnecterScanner.ExecuteReader("TRIGGERON", null);
                    start_St1ConnecterScanner = true;
                    rp300 = 1;
                }
                else
                {
                    WritePLC(DialTablePLC, result, "12");  //error code 2 for station 1 start failed caused by connection lost
                    WritePLC(DialTablePLC, ready, "False");                              //ready 
                    start_St1ConnecterScanner = false;
                }
            }
            if (start_St1ConnecterScanner)
            {
                if (DriverConnectStatus(St1ConnecterScanner))
                {
                    //Thread.Sleep(2000);
                    Driver.IExecuteReader IR = St1ConnecterScanner.ExecuteReader("READ", null);
                    if (IR.Success)
                    {
                        string snHousing = IR.Result.ToString().Trim('\0');
                        if (currentProductSettings.St1ConnectorCheckEnable)
                        {
                            rp300 += 1;
                            if (snHousing.Contains("NOREAD") || snHousing.Length == 0)
                            {
                                if (currentProductSettings.St1Connecter_PokaYoke)
                                {
                                    WritePLC(DialTablePLC, result, "1"); //ready
                                    WritePLC(DialTablePLC, ready, "True");
                                    start_St1ConnecterScanner = false;
                                    return;
                                }
                                else
                                {
                                    if (rp300 == 2)
                                    {
                                        St1ConnecterScanner.ExecuteReader("TRIGGERON", null);
                                        start_St1ConnecterScanner = true;
                                        return;
                                    }
                                    WritePLC(DialTablePLC, result, "11"); //read barcode error
                                    WritePLC(DialTablePLC, ready, "True");
                                    start_St1ConnecterScanner = false;
                                    return;
                                }
                            }
                            else
                            {
                                if (currentProductSettings.St1Connecter_PokaYoke)
                                {
                                    WritePLC(DialTablePLC, result, "11"); //read barcode error
                                    WritePLC(DialTablePLC, ready, "True");
                                    start_St1ConnecterScanner = false;
                                    return;
                                }
                            }

                            if (!currentProductSettings.St1Connecter_PokaYoke)
                            {
                                if (!snHousing.Contains(currentProductSettings.St1ConnectorSNRequirement.ToString()))
                                {
                                    WritePLC(DialTablePLC, result, "13"); //barcode not match
                                    WritePLC(DialTablePLC, ready, "True");
                                    start_St1HousingScanner = false;
                                    return;
                                }

                                ttt = Environment.TickCount - ttt;
                                System.Diagnostics.Debug.WriteLine("===================================================================================================");
                                System.Diagnostics.Debug.WriteLine(ttt.ToString());
                                System.Diagnostics.Debug.WriteLine("===================================================================================================");
                                WritePLC(DialTablePLC, result, "1"); //ready
                                WritePLC(DialTablePLC, ready, "True");
                                start_St1ConnecterScanner = false;
                            }

                            //Byte[] baT = Encoding.ASCII.GetBytes(snHousing);
                            //Byte[] baT2 = null;
                            //int[] iaT = null;
                            //BytesArrayTo2BytesArray(baT, out baT2);
                            //BytesArrayToIntArray(baT2, out iaT);
                            //WritePLC(DialTablePLC, "D7105", iaT.Length, iaT);
                        }
                        else
                        {
                            WritePLC(DialTablePLC, result, "1"); //ready
                            WritePLC(DialTablePLC, ready, "True");
                            start_St1ConnecterScanner = false;
                        }
                    }
                    //else
                    //{
                    //    St1ConnecterScanner.ExecuteReader("TRIGGEROFF", null);
                    //    rp300 += 1;
                    //    if (rp300 == 2)
                    //    {
                    //        St1ConnecterScanner.ExecuteReader("TRIGGERON", null);
                    //        start_St1ConnecterScanner = true;
                    //        return;
                    //    }
                    //    WritePLC(DialTablePLC, result, "11"); //read barcode error
                    //    WritePLC(DialTablePLC, ready, "True");
                    //    start_St1ConnecterScanner = false;
                    //}
                }
                else
                {
                    WritePLC(DialTablePLC, result, "12");  //connection lost
                    WritePLC(DialTablePLC, ready, "False");
                    start_St1ConnecterScanner = false;
                }
            }
            if (DetectRisingEdge(DialTablePLC, reset))
            {
                start_St1ConnecterScanner = false;

                try
                {
                    St1ConnecterScanner.ExecuteReader("EXIT", null);
                    St1ConnecterScanner.ExecuteReader("INIT", new object[] { this, base.myConfig.St1ConnecterScannerConfig });
                    if (DriverConnectStatus(St1ConnecterScanner))
                    {
                        WritePLC(DialTablePLC, result, "0");//reset success
                        WritePLC(DialTablePLC, ready, "True");
                    }
                    else
                    {
                        WritePLC(DialTablePLC, result, "12");//error code 1 for station 1 ,reset failed
                        WritePLC(DialTablePLC, ready, "False");
                    }
                }
                catch
                {
                    WritePLC(DialTablePLC, result, "12");//error code 1 for station 1 ,reset failed
                    WritePLC(DialTablePLC, ready, "False");
                }
            }
        }

        string Stn6HousingID = "";
        bool bGethousingID = false;
        int st5CameraStatus = 0;    //0:空闲，1：忙，2：OK，3：NG，4：Error&TimeOut
        int st5StatusShowTime = 0;
        private void AutoRunSt5Camera(string start, string result, string ok, string nok)
        {
            if (DetectRisingEdge(DialTablePLC, start))
            {
                //SendFeedBack("START_CAMERA", true, new int[] { 2, 1, 1 });//{a,b,c}: a=1 is busy, a=2 is finish;b=1 is pass, b=2 is fail; c= fault code
                if (ReadPLC<bool>(DialTablePLC, result))
                {
                    //int[] intSn = ReadPLC<int[]>(DialTablePLC, "D10034", 42);
                    //string housingID = PLCWordsToString(intSn).Substring(0, 21).Replace("\0", "");
                    string housingID = "";
                    int nestID = base.ReadPLC<int>(DialTablePLC, "E22590", 1);
                    List<string> list = HousingDB.SelectByNestID(nestID);
                    string[] housingList = list.ToArray();

                    if (housingList.Length > 0)
                    {
                        housingID = housingList[0];
                    }
                    if (housingID == "")
                    {
                        WritePLC(DialTablePLC, ok, "False");
                        WritePLC(DialTablePLC, nok, "True");
                        SendFeedBack("ASYNCMSG", true, "工站5相机不良模板检测错误,housingID未找到！");
                    }
                    else
                    {
                        if (housingID.Contains(currentProductSettings.St5RightPartNO))
                        {
                            WritePLC(DialTablePLC, nok, "False");
                            WritePLC(DialTablePLC, ok, "True");
                            bStn5ProductCheckResultOK = true;
                        }
                        else if (housingID.Contains(currentProductSettings.St5NegativePartNO))
                        {
                            WritePLC(DialTablePLC, ok, "False");
                            WritePLC(DialTablePLC, nok, "True");
                            bStn5ProductCheckResultNG = false;
                            SendFeedBack("ASYNCMSG", true, "工站5相机不良模板检测错误！");
                        }
                    }
                }
                else
                {

                    //SendFeedBack("START_CAMERA", true, new int[] { 2, 2, 1 });
                    //int[] intSn = ReadPLC<int[]>(DialTablePLC, "D10034", 42);
                    //string housingID = PLCWordsToString(intSn).Substring(0, 21).Replace("\0", "");
                    string housingID = "";
                    int nestID = base.ReadPLC<int>(DialTablePLC, "E22590", 1);
                    List<string> list = HousingDB.SelectByNestID(nestID);
                    string[] housingList = list.ToArray();

                    if (housingList.Length > 0)
                    {
                        housingID = housingList[0];
                    }

                    if (housingID == "")
                    {
                        WritePLC(DialTablePLC, ok, "False");
                        WritePLC(DialTablePLC, nok, "True");
                        SendFeedBack("ASYNCMSG", true, "工站5相机标准模板检测错误,housingID未找到！");
                    }
                    else
                    {
                        if (housingID.Contains(currentProductSettings.St5RightPartNO))
                        {
                            WritePLC(DialTablePLC, ok, "False");
                            WritePLC(DialTablePLC, nok, "True");
                            bStn5ProductCheckResultOK = false;
                            SendFeedBack("ASYNCMSG", true, "工站5相机标准模板检测错误！");
                        }
                        else if (housingID.Contains(currentProductSettings.St5NegativePartNO))
                        {
                            WritePLC(DialTablePLC, nok, "False");
                            WritePLC(DialTablePLC, ok, "True");
                            bStn5ProductCheckResultNG = true;
                        }
                    }
                }
            }

//             if (bStn5ProductCheckResultOK && bStn5ProductCheckResultNG)
//                 WritePLC(DialTablePLC, "E23203.00", "False");
        }

        //bomcheck
        public delegate Driver.IExecuteReader ExecuteReaderCaller(string command, params object[] parameters);  //定义个代理 
        ExecuteReaderCaller caller;
        IAsyncResult asyncResult;
        bool start_bomcheck = false;
        private void AutoRunSt3BomCheck(string reset, string start, string ready, string result)
        {
            long ttt = 0;
            bool startValue = ReadPLC<bool>(DialTablePLC, start);
            if (DetectRisingEdge(DialTablePLC, start))
            {
                ttt = Environment.TickCount;
                WritePLC(DialTablePLC, result, "5");//=5 means onging the process
                if (DriverConnectStatus(St12Trace))
                {
                    string housingId = string.Empty;
                    string partNr = currentProductSettings.Description;
                    string manuPartNr = currentProductSettings.Comments;

#if Debug_ITAC
                    //make test sn
                    string substring = sn.Substring(15, 3);
                    int subsn = Convert.ToInt32(substring);
                    subsn += 1;
                    string newsn = sn.Substring(0, 15) + subsn.ToString();

                    Byte[] baT = Encoding.ASCII.GetBytes(sn);
                    int[] iaT = null;
                    BytesArrayToIntArray(baT, out iaT);

                    WritePLC(DialTablePLC, "D7710", iaT.Length, iaT);
                    //WritePLC(DialTablePLC, "D7710", newsn);
                    //WritePLC(DialTablePLC, "D7710", newsn.Length, newsn);
                    
                    sn = newsn;
                    customerSn = subsn.ToString();
#else
                    //read sn
                    int[] intSn = ReadPLC<int[]>(DialTablePLC, "D7710", 15);
                    sn = PLCWordsToString(intSn);
                    sn = sn.Trim().Substring(0, 18);
                    if (sn == string.Empty || sn == "000000000000000000")
                    {
                        WritePLC(DialTablePLC, result, "13");   //no sn
                        WritePLC(DialTablePLC, ready, "True");
                        start_bomcheck = false;
                    }
#endif
                    if (currentProductSettings.St1HousingCheckEnable)
                    {
                        //read housingid
                        int[] intHousingId = ReadPLC<int[]>(DialTablePLC, "D7650", 15);
                        housingId = PLCWordsToString(intHousingId);
                        housingId = housingId.Trim('\0');
                        if (housingId == string.Empty)
                        {
                            WritePLC(DialTablePLC, result, "18");   //no housing id
                            WritePLC(DialTablePLC, ready, "True");
                            start_bomcheck = false;
                        }
                    }
                    //delayActive += 1;
                    //Driver.IExecuteReader IR;
                    //if (delayActive == 2 || materialBinNr == string.Empty)
                    //{
                    //    IR = St12Trace.ExecuteReader("ACTIVATE_MATERIAL_BOX", newMaterialNr);
                    //    if (IR.Success)
                    //    {
                    //        materialBinNr = newMaterialNr;
                    //    }
                    //    else
                    //    {
                    //        WritePLC(DialTablePLC, result, "17");   //activate material error
                    //        WritePLC(DialTablePLC, ready, "True");
                    //        start_bomcheck = false;
                    //        SendFeedBack("CHECK_MATERIAL_ERROR", true, null);
                    //        return;
                    //    }
                    //}
                    int[] intMaterialBinNr = ReadPLC<int[]>(DialTablePLC, "D7665", 15);
                    materialBinNr = PLCWordsToString(intMaterialBinNr);
                    materialBinNr = materialBinNr.Trim().Substring(0, 24);

                    St12Trace.ExecuteReader("BOM_CHECK2", sn, housingId, materialBinNr, manuPartNr);
                    WritePLC(DialTablePLC, ready, "False"); 
                    start_bomcheck = true;
                }
                else
                {
                    WritePLC(DialTablePLC, result, "11");  //error connection lost
                    WritePLC(DialTablePLC, ready, "False");  //ready 
                    start_bomcheck = false;
                }
            }
            if (start_bomcheck)
            {
                if (!DriverConnectStatus(St12Trace))
                {
                    WritePLC(DialTablePLC, result, "11");  //connection lost
                    WritePLC(DialTablePLC, ready, "False");                              //ready 
                    start_bomcheck = false;
                    return;
                }
                Driver.IExecuteReader IR = St12Trace.ExecuteReader("BOM_CHECK_STATUS");
                int[] ret = (int[])IR.Result;
                if (IR.Success)
                {
                    if (ret[0] == 0)
                    {
                        int materialQuantity = (int)ret[1];
                        int materialTotalQuantity = (int)ret[2];
                        object obj = (object)(new object[] { (int)ret[1], (int)ret[2] });
                        SendFeedBack("MATERIAL_QUANTITY", true, obj);
                        if (materialQuantity == 1)
                        {
                            //ShowMaterialError();
                            SendFeedBack("ASYNCMSG", true, "物料已经用完，请扫描新的物料箱号！");
                        }
                        ttt = Environment.TickCount - ttt;
                        System.Diagnostics.Debug.WriteLine("st3 time: " + ttt);

                        //Byte[] baT = Encoding.ASCII.GetBytes(materialQuantity.ToString());
                        //Byte[] baT2 = null;
                        //int[] iaT = null;
                        //BytesArrayTo2BytesArray(baT, out baT2);
                        //BytesArrayToIntArray(baT2, out iaT);
                        //WritePLC(DialTablePLC, "E2236", iaT.Length, iaT);
                        WritePLC(DialTablePLC, "E2236", materialQuantity.ToString());

                        WritePLC(DialTablePLC, result, "1"); //OK
                        WritePLC(DialTablePLC, ready, "True");
                        start_bomcheck = false;
                        //if (materialQuantity <= 0)
                        //    materialBinNr = string.Empty;       
                    }
                    else
                    {
                        switch (ret[0])
                        {
                            case -1014:
                                {
                                    WritePLC(DialTablePLC, result, "14");   //sn not found
                                }
                                break;
                            case -1015:
                                {
                                    WritePLC(DialTablePLC, result, "15");   //partNr not correct
                                }
                                break;
                            case -1016:
                                {
                                    WritePLC(DialTablePLC, result, "16");   //append housing id error
                                }
                                break;
                            case -1017:
                                {
                                    WritePLC(DialTablePLC, result, "17");   //activate material error
                                }
                                break;
                            default:
                                {
                                    WritePLC(DialTablePLC, result, "12");   //bom check error
                                }
                                break;
                        }
                        WritePLC(DialTablePLC, ready, "True");
                        start_bomcheck = false;
                    }
                }
            }
            if (DetectRisingEdge(DialTablePLC, reset))
            {
                start_bomcheck = false;
                St12Trace.ExecuteReader("EXIT", null);
                St12Trace.ExecuteReader("INIT", new object[] { this, base.myConfig.St12Trace });
                if (DriverConnectStatus(St12Trace))
                {
                    WritePLC(DialTablePLC, result, "0");//reset success
                    WritePLC(DialTablePLC, ready, "True");
                }
                else
                {
                    WritePLC(DialTablePLC, result, "11");//error code 1 for station 1 ,reset failed
                    WritePLC(DialTablePLC, ready, "False");
                }
            }
        }

        bool start_ECheck = false;
        string ecusn = string.Empty;
        private void AutoRunSt6ECheck(string reset, string start, string ready, string result)
        {
            if (DetectRisingEdge(DialTablePLC, start))
            {
                int[] intSn = ReadPLC<int[]>(DialTablePLC, "D8510", 8);
                string materialSN1 = PLCWordsToString(intSn).Substring(0, 16);
                intSn = ReadPLC<int[]>(DialTablePLC, "D8534", 8);
                string materialSN2 = PLCWordsToString(intSn).Substring(0, 16);


                ecusn = string.Empty;
                WritePLC(DialTablePLC, result, "5");//=5 means onging the process
                if (DriverConnectStatus(St6ECheck))
                {
                    WritePLC(DialTablePLC, ready, "False");                                //ready 
                    start_ECheck = true;
                }
                else
                {
                    WritePLC(DialTablePLC, result, "11");  //error code 2 for station 1 start failed caused by connection lost
                    WritePLC(DialTablePLC, ready, "False");                              //ready 
                    start_ECheck = false;
                }
            }
            if (start_ECheck)
            {
                //Thread.Sleep(200);
                //WritePLC(DialTablePLC, result, "1"); //ready
                //WritePLC(DialTablePLC, ready, "True");
                if (DriverConnectStatus(St6ECheck))
                {
                    for (int i = 0; i < 2; i++)
                    {
                        Driver.IExecuteReader IR = St6ECheck.ExecuteReader("GETECUSN", null);
                        if (IR.Success)
                        {
                            object[] myobj = (object[])IR.Result;
                            ecusn = myobj[1].ToString().Substring(0, 18);
                            WritePLC(DialTablePLC, result, "1"); //ready
                            WritePLC(DialTablePLC, ready, "True");
                            start_ECheck = false;
                            SendFeedBack("ECUSN", true, ecusn);
                            return;
                        }
                        Thread.Sleep(200);
                    }
                    WritePLC(DialTablePLC, result, "12");  //error
                    WritePLC(DialTablePLC, ready, "False");  //ready 
                    start_ECheck = false;
                    SendFeedBack("ECUSN", true, "NO READ");
                }
                else
                {
                    WritePLC(DialTablePLC, result, "11");  //connection lost
                    WritePLC(DialTablePLC, ready, "False");  //ready 
                    start_ECheck = false;
                }
            }
            if (DetectRisingEdge(DialTablePLC, reset))
            {
                start_ECheck = false;
                St6ECheck.ExecuteReader("EXIT", null);
                St6ECheck.ExecuteReader("INIT", new object[] { this, base.myConfig.St6ECheckConfig });
                St6ECheck.ExecuteReader("LOADCANDLL", currentProductSettings.St6CanDll.ToString());
                if (DriverConnectStatus(St6ECheck))
                {
                    WritePLC(DialTablePLC, result, "0");//reset success
                    WritePLC(DialTablePLC, ready, "True");
                }
                else
                {
                    WritePLC(DialTablePLC, result, "11");//error code 1 for station 10 ,reset failed
                    WritePLC(DialTablePLC, ready, "False");
                }
            }
        }

        //upload state
        bool start_uploadState = false;
        string st12CustomerSn = string.Empty;
        private void AutoRunSt8UploadState(string reset, string start, string ready, string result)
        {
            long ttt = 0;
            bool startValue = ReadPLC<bool>(DialTablePLC, start);
            if (DetectRisingEdge(DialTablePLC, start))
            {

                if (bTrialRun)
                {
                    WritePLC(DialTablePLC, result, "5");//=5 means onging the process
                    WritePLC(DialTablePLC, ready, "False");   //ready 
                    Thread.Sleep(200);
                    WritePLC(DialTablePLC, result, "1"); //no sn
                    WritePLC(DialTablePLC, ready, "True");
                    return;
                }
                ttt = Environment.TickCount;
                WritePLC(DialTablePLC, result, "5");//=5 means onging the process
                if (!DriverConnectStatus(St12Trace))
                {
                    WritePLC(DialTablePLC, result, "11");  //error connection lost
                    WritePLC(DialTablePLC, ready, "False");
                    start_uploadState = false;
                    return;
                }

                WritePLC(DialTablePLC, ready, "False");   //ready 
                start_uploadState = true;
            }
            if (start_uploadState)
            {
                if (!DriverConnectStatus(St12Trace))
                {
                    WritePLC(DialTablePLC, result, "11");  //error connection lost
                    WritePLC(DialTablePLC, ready, "False");
                    start_uploadState = false;
                    return;
                }
                int failStation = ReadPLC<int>(DialTablePLC, "E12818");
                //string sn = GetSn(8);
                sn = ecusn;
                if (sn == string.Empty )
                {
                    WritePLC(DialTablePLC, result, "13"); //no sn
                    WritePLC(DialTablePLC, ready, "True");
                    start_uploadState = false;
                    return;
                }
                //int[] intSn = ReadPLC<int[]>(DialTablePLC, "D9110", 8);
                //string materialSN1 = "9S000000" + PLCWordsToString(intSn).Substring(0, 16);
                //intSn = ReadPLC<int[]>(DialTablePLC, "D9134", 8);
                //string materialSN2 = "9S000000" + PLCWordsToString(intSn).Substring(0, 16);
                //string[] materialList=null;
                //if (st1MaterialArray.Rows.Count==1)
                //{
                //    materialList = new string[1];
                //    materialList[0]=materialSN1;
                //}
                //else if (st1MaterialArray.Rows.Count==2)
                //{
                //    materialList = new string[2];
                //    materialList[0]=materialSN1;
                //    materialList[1]=materialSN2;
                //}

                int nestID = base.ReadPLC<int>(DialTablePLC, "E22690", 1);
                List<string> list = ItacDB.SelectByNestID(nestID);
                string[] materialList = list.ToArray();
                if (materialList == null || materialList.Length <= 0)
                {
                    WritePLC(DialTablePLC, result, "16"); //no material sn
                    WritePLC(DialTablePLC, ready, "True");
                    start_uploadState = false;
                    return;
                }
                bool[] enableArray = new bool[8];
                for (int i = 0; i < 8; i++)
                {
                    string address = "E2007." + i.ToString();
                    bool a = ReadPLC<bool>(DialTablePLC, address);
                    enableArray[i] = !a;
                }
                Driver.IExecuteReader IR = St12Trace.ExecuteReader("CHECK_CONNECTION", "NOTHING");
                if (!IR.Success)
                {
                    SendFeedBack("CHECK_CONNECTION", true, null);
                    return;
                }
                IR = St12Trace.ExecuteReader("UPLOADSTATE", sn, failStation, currentProductSettings.St8DispathQuantity, currentProductSettings.St8DispathPrinterFile, currentProductSettings.St8NeedDispatch, materialList , enableArray);
                if (IR.Success)
                {
                    WritePLC(DialTablePLC, result, "1"); //ready
                    WritePLC(DialTablePLC, ready, "True");
                    start_uploadState = false;

                    int sum = 0;
                    for (int i = 0; i < 7; i++)
                    {
                        //E2510;E2505;E2520;E2521;E2522;E2523;E2524;E2525;E2526;E2527;E2007;E2504;E2800
                        string address = "E" + (2520 + i).ToString();
                        int a = ReadPLC<int>(DialTablePLC, address);
                        if (a != 0)
                            sum += 1;
                    }
                    object[] obj = (object[])IR.Result;
                    activeMaterialArray = (DataTable)obj[2];
                    if (activeMaterialArray != null && st1MaterialArray != null)
                    {
                        foreach (DataRow dr in activeMaterialArray.Rows)
                        {
                            foreach (DataRow drSt1 in st1MaterialArray.Rows)
                            {
                                if (dr["partNo"].ToString() == drSt1["partNo"].ToString())
                                {
                                    drSt1["activeSn"] = dr["sn"];
                                    drSt1["activeQuantity"] = dr["quantity"];
                                }
                            }
                        }
                    }
                    SendFeedBack("UPLOADSTATE", true, (object)(new object[] { sn, obj[1], currentProductSettings.St8DispathQuantity, activeMaterialArray ,sum}));
                }
                else
                {
                    object[] obj = (object[])IR.Result;
                    if (int.Parse(obj[0].ToString()) == -1001)
                    {
                        WritePLC(DialTablePLC, result, "15"); //active material error
                    }
                    else
                    {
                        WritePLC(DialTablePLC, result, "14"); //upload state error
                    }
                    WritePLC(DialTablePLC, ready, "True");
                    start_uploadState = false;
                    string str = "Itac 错误信息：" + obj[3].ToString();
                    //ShowMSG(str);
                    SendFeedBack("ASYNCMSG", true, str);
                }
            }
            if (DetectRisingEdge(DialTablePLC, reset))
            {
                start_uploadState = false;
                St12Trace.ExecuteReader("EXIT", null);
                St12Trace.ExecuteReader("INIT", new object[] { this, base.myConfig.St12Trace });
                if (DriverConnectStatus(St12Trace))
                {
                    WritePLC(DialTablePLC, result, "0");//reset success
                    WritePLC(DialTablePLC, ready, "True");
                }
                else
                {
                    WritePLC(DialTablePLC, result, "12");//error code 1 for station 1 ,reset failed
                    WritePLC(DialTablePLC, ready, "False");
                }
            }
        }

        //show customer sn
        private void AutoRunSt1AddToBox(string reset, string start, string ready, string result)
        {
            if (DetectRisingEdge(DialTablePLC, start))
            {
                string csn = GetCustomerSn(1);
                SendFeedBack("CUSTOMER_SN", true, csn);
                if (csn == lastCSN)
                {
                    WritePLC(DialTablePLC, "E2231", "1");
                    SendFeedBack("DISPATCH_OVER", true, null);
                }
            }
        }


        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }

        protected void BytesArrayTo2BytesArray(byte[] indata, out byte[] outdata)
        {
            

            outdata = null;
            if (indata.Length % 2 > 0)
            {
                outdata = new byte[indata.Length + 1];

                for (int i = 0; i < outdata.Length; i++)
                {
                    outdata[i] = 0;
                }
                Array.Copy(indata, outdata, indata.Length);
            }
            else
            {
                outdata = new byte[indata.Length];
                Array.Copy(indata, outdata, indata.Length);
          
            }
        }

        protected void BytesArrayToIntArray(byte[] indata, out int[] outdata)
        {
            outdata = null;

            if (indata.Length % 2 > 0)
            {
                return;
            }

            outdata = new int[indata.Length / 2];

            for (int i = 0; i < outdata.Length; i++)
            {
                int t_n = (int)indata[2 * i] * 256;
                t_n = t_n + (int)indata[2 * i + 1];

                outdata[i] = t_n;
            }
        }


        private bool messageBoxClickedResult = false;
        private void ShowMaterialError()
        {
            SendAsyncFeedBack("DisplayMessageBox", "物料已经用完，请扫描新的物料箱号！",
                (result) =>
                {
                    messageBoxClickedResult = (bool)result;
                });
        }

        private void ShowMSG(string msg)
        {
            SendAsyncFeedBack("DisplayMessageBox", msg,
                (result) =>
                {
                    messageBoxClickedResult = (bool)result;
                });
        }

        private void SendAsyncFeedBack(string command, object data, Action<object> finishedCall)
        {
            command = "ASYNC_COMMAND_" + command;
            object[] sendData = new object[2];
            sendData[0] = finishedCall;
            sendData[1] = data;
            SendFeedBack(command, true, sendData);
        }
    }
}
